package com.dw.widget.slideshow.thread;

import com.dw.widget.slideshow.db.helper.ImageDBHelper;
import com.dw.widget.slideshow.db.object.ImageData;
import com.dw.widget.slideshow.objects.Size;
import com.dw.widget.slideshow.utils.ApplicationEx;
import com.dw.widget.slideshow.utils.ImageUtils;
import com.dw.widget.slideshow.utils.log.Log;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Process;

public class AddClipsThread extends Thread {

	private final ApplicationEx _APP = ApplicationEx.INSTANCE();
	private final String TAG = "AddClipsThread";
	private final int CACHE_LENGTH = 10;
	
	private Context mContext;
	private Handler mHandler;
	
	private int mCount;
	
	public AddClipsThread(Context context, Handler handler, int count)
	{
		mContext = context;
		mHandler = handler;
		mCount = count;
		
		Process.setThreadPriority(MAX_PRIORITY);
	}
	
	@Override
	public void run()
	{	
		ImageDBHelper dbHelper = new ImageDBHelper(mContext, _APP.DB_NAME, ImageData.class);
		
		for(int i = 0; i < mCount; i++)
		{
			// 缓存中没有了则再读取
			if(_APP.IMAGE_CACHE.getLeft() <= 0)
			{
				ImageData[] images = dbHelper.getRandomImages(CACHE_LENGTH);
				_APP.IMAGE_CACHE.setImageCache(images);
			}

			// 取出随机图片
			ImageData nextImage = _APP.IMAGE_CACHE.getNext();
			String path = nextImage.getPicturePath();
			String clipPath = nextImage.getClipPath();
			String name = nextImage.getName();
			String orientation = nextImage.getOrientation();
			Log.d(mContext, TAG, String.format("addClips path=%1$s", path));
			
			Bitmap[] clips = null;
			if(clipPath == null || "".equals(clipPath))
			{
				Log.d(mContext, TAG, String.format("use IMAGE file %1$s", path));
				Bitmap bmp = ImageUtils.ZoomOut(path, new Size(_APP.widgetWidthPx, _APP.widgetHeightPx));
				clips = ImageUtils.splitImage(bmp, (float)_APP.widgetWidthPx/(float)_APP.widgetHeightPx);
				
				// 把clip存成文件用于下次读取
				String imageName = name.substring(0, name.lastIndexOf("."));
				String clipSavePath = _APP.CLIP_DIR + imageName + _APP.CLIP_SUFFIX;
				ImageUtils.Serialize2File(clips, clipSavePath);
				nextImage.setClipPath(clipSavePath);
				
				synchronized (_APP.DB_MODIFY_LOCK) {
					dbHelper.update(nextImage);
				}
			}
			else   // 已有文件缓存
			{
				Log.d(mContext, TAG, String.format("use CLIP file %1$s", clipPath));
				clips = ImageUtils.DeserializeFromFile(clipPath);
			}
			
			_APP.CLIP_QUEUE.enQueue(clips, orientation);
		}
		
		if(mHandler != null)
		{
			mHandler.sendEmptyMessage(_APP.THREAD_MSG_ADDCLIP);
		}
	}
}
